package com.newland.zxy;

import java.sql.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import static com.newland.zxy.MyPropertiesUtil.getProperties;
import static com.newland.zxy.MyPropertiesUtil.getValueForString;

/**
 * @author zhangxuyuan
 * @version 1.0
 * @date 2021/1/12
 */
public class DBUtil {
    private static Logger logger = LogManager.getLogger(DBUtil.class);

    /**
     * 关闭数据库连接
     *
     * @param con
     * @param preparedStatement
     * @param resultSet
     */
    public static void close(Connection con, PreparedStatement preparedStatement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static Connection getCon() {

        if (MyPropertiesUtil.props == null) {
            getProperties();
        }
        Connection con = null;
        try {
            Class.forName(getValueForString("driverClassName"));
            logger.info("加载驱动成功！");
            //获取数据库连接
            logger.info(getValueForString("driverClassName"));
            logger.info(getValueForString("url"));
            logger.info(getValueForString("username"));
            logger.info(getValueForString("password"));
            con = DriverManager.getConnection(getValueForString("url"), getValueForString("username"),
                getValueForString("password"));
            logger.info("获取数据库连接成功！");
            logger.info("进行数据库操作！");
        } catch (SQLException e) {
            logger.error("SQLException error ", e);
            logger.error("获取数据库连接失败！");
        } catch (ClassNotFoundException e) {
            logger.error("ClassNotFoundException error ", e);
            logger.error("数据库驱动未找到。请确认包是否存在！");
        }
        return con;

    }

}
